import {
	SerializedError,
	createAsyncThunk,
	createSlice,
} from '@reduxjs/toolkit'
import { RootState, TCatalogData } from '../../types'
import api from '../../../api'
import { TCatalogRequest, TCatalogResponse } from '../../../api/api'
import {
	DEFAULT_ITEMS_PER_PAGE,
	DEFAULT_PAGE,
} from '../../../components/cardlist/pagination'

type TCatalogState = {
	data: TCatalogData[] | null
	quantity: number
	pagination: {
		itemsPerPage: number
		selectedPage: number
		maxPage: number
	}
	loading: boolean
	error: SerializedError | null | unknown
}

const initialState: TCatalogState = {
	data: null,
	quantity: 0,
	pagination: {
		itemsPerPage: DEFAULT_ITEMS_PER_PAGE,
		selectedPage: DEFAULT_PAGE,
		maxPage: DEFAULT_PAGE,
	},
	loading: false,
	error: null,
}

const sliceName = 'catalog'

export const fetchCatalog = createAsyncThunk<TCatalogResponse, TCatalogRequest>(
	`${sliceName}/fetchCatalog`,
	async (params, { getState }) => {
		try {
			const response = await api(
				(getState() as RootState).user.token
			).getProducts(params)
			return response
		} catch (error) {
			return error
		}
	}
)

export const catalogSlice = createSlice({
	name: sliceName,
	initialState,
	reducers: {
		setPage: (state, action) => {
			state.pagination.selectedPage = action.payload
		},
		setQuantity: (state, action) => {
			state.quantity = action.payload
		},
	},
	extraReducers: (builder) => {
		builder
			.addCase(fetchCatalog.fulfilled, (state, action) => {
				state.pagination.maxPage = Math.ceil(
					action.payload.total / DEFAULT_ITEMS_PER_PAGE
				)
				state.quantity = action.payload.total
				state.data = action.payload.products
				state.loading = false
			})
			.addCase(fetchCatalog.pending, (state) => {
				state.loading = true
				state.error = null
			})
			.addCase(fetchCatalog.rejected, (state, action) => {
				state.error = action.payload
				state.loading = false
			})
	},
})
